package com.hangxingliu.exceltools;

import javax.swing.JDialog;
import javax.swing.JScrollPane;

import java.awt.BorderLayout;

import javax.swing.JPanel;
import javax.swing.JButton;

import java.awt.FlowLayout;

import javax.swing.JTextPane;

import java.awt.Toolkit;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class HelpDialog extends JDialog{
	private static final long serialVersionUID = -6675940083547407069L;
	
	private JScrollPane scrollPane;
	private JPanel panel;
	private JButton button;
	private JTextPane textPane;

	public HelpDialog() {
		setAlwaysOnTop(true);
		setIconImage(Toolkit.getDefaultToolkit().getImage(HelpDialog.class.getResource("/com/hangxingliu/exceltools/about.png")));
		
		setTitle("帮助&关于 ".concat(Application.VERSION));
		setDefaultCloseOperation(HIDE_ON_CLOSE);
		
		scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		
		textPane = new JTextPane();
		textPane.setFocusable(false);
		textPane.setEditable(false);
		textPane.setContentType("text/html");
		textPane.setText(loadAboutText());
		scrollPane.setViewportView(textPane);
		
		panel = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel.getLayout();
		flowLayout.setAlignment(FlowLayout.RIGHT);
		getContentPane().add(panel, BorderLayout.SOUTH);
		
		button = new JButton("确定");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
			}
		});
		panel.add(button);
		
	}
	
	public void showWind(int x,int y,int w,int h){
		setBounds(x,y,w,h);
		textPane.setSelectionStart(0);
		textPane.setSelectionEnd(0);
		setVisible(true);
	}
	
	private String loadAboutText(){
		String content = "<html><body>帮助文档加载出错!</html></body>";
		URL url = HelpDialog.class.getResource("/com/hangxingliu/exceltools/about.html");
		if(url == null)
			return content;
		byte[] dat = new byte[1<<13];
		try {
			InputStream is = url.openStream();
			int len = is.read(dat);
			content = new String(dat,0,len,Application.CHARSET);
			content = "<html><body>".concat(content).concat("</body></html>");
			content = replaceParam(content);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
			return content;
		}
		return content;
	}
	
	private String replaceParam(String content){
		content = content.replace("{{VERSION}}", Application.VERSION);
		content = content.replace("{{PROJECT_URL}}", Application.PROJECT_URL);
		content = content.replace("{{AUTHOR}}", Application.AUTHOR);
		content = content.replace("{{DATE}}", Application.DATE);
		return content;
	}
}
